package main

import (
	"bufio"
	"encoding/binary"
	"fmt"
	"io"
	"math/rand"
	"net"
	"os"
	"strings"
	"time"
)

func readFileToSlice(filename string) (slice []string, err error) {

	slice = make([]string, 0)

	// 打开文件
	file, err := os.Open(filename)

	if err != nil {
		fmt.Printf("Open file error: %v\n", err)
		return nil, err
	}

	defer file.Close()

	// 创建reader
	reader := bufio.NewReader(file)

	// 读取文件内容
	for {

		line, err := reader.ReadString('\n')

		if err == io.EOF {
			break
		}

		if err != nil {
			fmt.Printf("Read line error: %v\n", err)
			return nil, err
		}

		slice = append(slice, strings.TrimRight(line, "\n"))
	}

	return slice, nil
}

func write(conn net.Conn, data []byte) (int, error) {

	// 写数据长度
	var pkgLen = uint32(len(data))
	var bytes [4]byte
	binary.BigEndian.PutUint32(bytes[0:4], pkgLen)
	n, err := conn.Write(bytes[:4])

	if err != nil {
		fmt.Printf("Write data length error=%v\n", err)
		return n, err
	}

	// 写数据
	n, err = conn.Write(data)

	if err != nil {
		fmt.Printf("Write data error=%v\n", err)
		return n, err
	}

	return n, err
}

func main() {

	var filename = "D:\\IdeaProjects\\go-study\\basic-go\\src\\tcp-demo\\kafka-demo\\producer\\main.go"

	// 读取文件把里面的内容封装到一个切片里面
	slice, err := readFileToSlice(filename)
	if err != nil {
		fmt.Printf("Read slice error: %v\n", err)
	}

	address := "127.0.0.1:9999"

	// 建立连接
	conn, err := net.Dial("tcp", address)

	// 关闭连接
	defer conn.Close()

	if err != nil {
		fmt.Printf("Net connect error=%v\n", err)
		return
	}

	rand.Seed(time.Now().UnixNano())

	for i := 0; i < 1000000; i++ {
		// 循环遍历切片，向服务器发送
		for _, line := range slice {
			// 写数据
			_, err = write(conn, []byte(line))
			//_, err := conn.Write([]byte(line))
			if err != nil {
				fmt.Printf("Write line error=%v\n", err)
			}
		}
		write(conn, []byte("--- 华丽的分割线 ---"))
		//conn.Write([]byte("--- Dividing line ---"))
		time.Sleep(time.Microsecond * time.Duration(rand.Int63n(100)))
	}
}
